package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utils.Utils;
import utils.XmlParser;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import define.API;
import define.Key;
import define.SharedPreference;

public class GetTokenString extends AsyncTask<Void, Void, Boolean> {

	private static final String TAG = GetTokenString.class.getSimpleName();

	private boolean GET_DATA = false;

	private static final String KEY_RESULT = "result"; // parent node
	private static final String KEY_TOKEN = "token";

	private static String PASSWORD = null, USER_NAME = null;

	public static String TOKEN_STRING = null;

	private Context context;
	private Utils connectivity = null;

	public GetTokenString(Context context, boolean get_data) {
		this.context = context;
		this.GET_DATA = get_data;

		// Get shared preferences
		SharedPreferences mSpSettings = context.getSharedPreferences(
				SharedPreference.PREFS, Context.MODE_PRIVATE);

		USER_NAME = mSpSettings.getString(
				SharedPreference.PREFS_KEY_LOGIN_NAME, "0");
		PASSWORD = mSpSettings.getString(SharedPreference.PREFS_KEY_PASSWORD,
				"0");

		connectivity = new Utils(context);
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		return getTokenString();
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		connectivity.showProgressDialog();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		// Change the class in here
		Class<?> object = null;
		try {
			object = Class.forName(context.getClass().getName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		if (!result) {
			connectivity.showConnectionTimeoutDialog(context, object);
		} else {
			// Get information array list
			if (GET_DATA) {
				try {
					Thread.sleep(1200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				new GetItemInAllTabs(context).execute();
			}
		}
		connectivity.hideProgressDialog();
	}

	/**
	 * Basic methods
	 */
	public boolean getTokenString() {
		HttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mHttpPost = new HttpPost(API.MP_TOKEN_REQUEST);

		List<NameValuePair> mListNameValue = new ArrayList<NameValuePair>(2);

		mListNameValue.add(new BasicNameValuePair(
				SharedPreference.PREFS_KEY_USER_NAME, USER_NAME));
		mListNameValue.add(new BasicNameValuePair(Key.KEY_PASWORD, PASSWORD));

		try {
			mHttpPost.setEntity(new UrlEncodedFormEntity(mListNameValue));

			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			XmlParser mXMLParserGetToken = new XmlParser();
			Document mDocument = mXMLParserGetToken.getDomElement(XML);

			NodeList mNodeList = mDocument.getElementsByTagName(KEY_RESULT);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) mNodeList.item(i);
					TOKEN_STRING = mXMLParserGetToken.getValue(element,
							KEY_TOKEN);
				}
			}

			Log.i(TAG, "TOKEN_STRING " + TOKEN_STRING);

			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
